import { NextApiRequest, NextApiResponse } from 'next';
import OpenAI from 'openai';

if (!process.env.OPENAI_API_KEY) {
  throw new Error('Missing OPENAI_API_KEY environment variable');
}

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const detectLanguage = async (text: string): Promise<string> => {
  try {
    const response = await openai.chat.completions.create({
      model: "gpt-3.5-turbo",
      messages: [
        {
          role: "system",
          content: "You are a language detection expert. Respond only with the ISO 639-1 language code (e.g., 'en', 'zh', 'ja', etc.)."
        },
        {
          role: "user",
          content: `Detect the language of this text: "${text}"`
        }
      ],
      temperature: 0.3,
      max_tokens: 10,
    });

    return response.choices[0]?.message?.content?.trim().toLowerCase() || 'en';
  } catch (error) {
    console.error('Language detection error:', error);
    return 'en'; // Default to English on error
  }
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { text, source_language, target_language } = req.body;

    if (!text || !target_language) {
      return res.status(400).json({ error: 'Missing required parameters' });
    }

    // Detect language if source_language is 'auto'
    const detected_language = source_language === 'auto' 
      ? await detectLanguage(text)
      : source_language;

    const prompt = `Translate the following text from ${detected_language} to ${target_language}:\n\n${text}`;

    const response = await openai.chat.completions.create({
      model: "gpt-3.5-turbo",
      messages: [
        {
          role: "system",
          content: "You are a professional translator. Provide only the direct translation without any explanations or additional text."
        },
        {
          role: "user",
          content: prompt
        }
      ],
      temperature: 0.3,
      max_tokens: 1000,
    });

    const translation = response.choices[0]?.message?.content?.trim() || '';
    res.status(200).json({ 
      translation,
      detected_language: detected_language
    });
  } catch (error) {
    console.error('Translation error:', error);
    res.status(500).json({ error: '翻译服务出错，请稍后重试' });
  }
}